package cn.qayy.controller;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.qayy.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;

import cn.qayy.po.User;
import cn.qayy.service.IUserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 远程调试，tomcat部署war包，以catalina.bat jpda start 命令在cmd中启动，打开并查看远程端口。
     * new Remote 配置好远程端口，打断点，debug方式启动本地，这时访问远程服务器的应用就能在本地debug了。
     *
     * @param response
     * @param request
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/toLogin.do")
    public JsonResult toLogin(HttpServletResponse response, HttpServletRequest request,
                              String username, String password, String[] holdPassword, String cookiePassword, ModelMap model) {
        /**
         * 这里的参数应该与页面的input元素的name一一对应，才能接收得到
         * var params = $("#login").serialize();表单form序列化，也可以通过对象（属性应该与input的name一一对应）来接收
         *
         * toLogin()方法的参数个数不一定与前台页面的form里的参数name一致，但是名字要一一对应一致才能接收，参数个数很灵活
         */
        Map<String, Object> data = new HashMap<String, Object>();

        /**
         * session方案
         * 生成的验证码存放在session里，用于与用户输入的验证码进行对比，是否输入正确
         */
        HttpSession session = request.getSession();

        /***
         * params用于存放参数
         */
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", username);
        if ("true".equals(cookiePassword)) {
            if(password != null&&password.length()==32){
                params.put("password", password);
            } else {
                params.put("password", MyMD5.toMd5(password));
            }
        } else {
            params.put("password", MyMD5.toMd5(password));
        }
        User user = userService.loginUser(params);
        if (user != null) {// 说明当前用户存在
            /***
             * 基础库里存放了当前的业务经理的地区映射等情况
             */
            Map<String, Object> usersParams = new HashMap<String, Object>();
            usersParams.put("user_name",user.getUser_name());
            Integer count = userService.isExistsFromBasicLib(usersParams);
            if(user.getLev()>=1){//具有下载全国流向的权限，可以绕过基础库登陆
                count = 1;
            }
            if(count != null && count >=1 ){//说明在基础库中存在，具有登陆的权限
                data.put("user", user);
                /***
                 * session里存放一个对象。
                 */
                session.setAttribute("user", user);
                session.setAttribute("username", user.getUser_name());
                session.setAttribute("isLoginIndex",true);
                session.setAttribute("hobby", user.getHobby());
                //用户点击了记住密码
                if (holdPassword != null && holdPassword.length >= 1) {
                    //在客户端的浏览器中保存一个cookie对象。
                    String cval = CookieUtil.getCookie(request, "userId");
                    if (cval == null) {
                        /***
                         * cookie方案
                         * 创建一个cookie对象，指定cookie的名字，和cookie对象存放String类型的值，并进行编码，防止中文乱码。
                         * 通过服务器响应浏览器上，通过response对象把cookie给浏览器。
                         */
                        Cookie cookie = new Cookie("userId", UrlUtil.encode(user.getId() + ""));
                        //设置时间为1年
                        cookie.setMaxAge(365 * 24 * 3600);
                        cookie.setPath("/");
                        //把cookie给浏览器
                        response.addCookie(cookie);
                    }
                }
            } else {
                data.put("message", "请联系流向岗，如实告知您负责的省份，让其为您授权！授权后，您将能查看和下载对应省份的流向！");
            }
        } else {
            data.put("message", "用户名/密码  输入错误！");
        }
        JSONObject json = new JSONObject();
        json.put("data", data);
        ResonseUtils.writeResponseByJson(response, json);
        //System.out.println("toLogin()方法已经执行完。");
        //System.out.println("message="+data.get("message"));
        return null;
    }

    @RequestMapping(value = "/getCurrentLoginUser.do")
    public JsonResult getCurrentLoginUser(HttpServletResponse response, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            JSONObject json = new JSONObject();
            json.put("user", user);
            ResonseUtils.writeResponseByJson(response, json);
        }
        return null;
    }


    /**
     * 修改密码
     *
     * @param response
     * @param request
     * @param passwordOld
     * @param passwordNew
     * @param model
     * @return
     */
    @RequestMapping(value = "/updatePassword.do")
    public JsonResult updatePassword(HttpServletResponse response, HttpServletRequest request,
                                     String passwordOld, String passwordNew, ModelMap model) {
        Map<String, Object> data = new HashMap<String, Object>();
        User user = (User) request.getSession().getAttribute("user");
        Map<String, Object> params = new HashMap<String, Object>();
        //System.out.println(user.getUser_name());
        if (user != null) {// 说明当前用户存在
            if (user.getPassword().equals(MyMD5.toMd5(passwordOld))) {//说明输入的当前密码正确
                params.put("password", MyMD5.toMd5(passwordNew));
                params.put("id", user.getId());
                try {
                    userService.updatePassword(params);
                    data.put("message", "修改成功！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                data.put("error", "输入的当前密码不正确！");
            }
        } else {
            data.put("error", "登录已经过期，请重新登录！");
        }
        JSONObject json = new JSONObject();
        json.put("data", data);
        ResonseUtils.writeResponseByJson(response, json);
        System.out.println("updatePassword()方法已经执行完。");
        return null;
    }

    @RequestMapping(value = "/selectUserNameAndPassword.do")
    public JsonResult selectUserNameAndPassword(HttpServletResponse response, HttpServletRequest request, ModelMap model) {
        Map<String, Object> data = new HashMap<String, Object>();
        String userId = CookieUtil.getCookie(request, "userId");
        Map<String, Object> params = new HashMap<String, Object>();
        if (userId != null) {// 说明用户记住了密码
            User user = userService.selectById(Integer.parseInt(userId));
            if (user != null) {
                data.put("message", "suceessful");
                data.put("userName", user.getUser_name());
                data.put("password", user.getPassword());
            }
        }
        JSONObject json = new JSONObject();
        json.put("data", data);
        ResonseUtils.writeResponseByJson(response, json);
        //System.out.println("selectUserNameAndPassword()方法已经执行完。");
        return null;
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        return "index";
    }
    @RequestMapping("/index2")
    public String index2(HttpServletRequest request) {
    	return "index2";
    }
    @RequestMapping("/update_password")
    public String update_password(HttpServletRequest request) {
    	return "update_password";
    }

    //测试myBatis的方法
    @RequestMapping("/showUser")
    public String toIndex(HttpServletRequest request, Model model) {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.selectById(userId);
        model.addAttribute("user", user);
        return "showUser";
    }
}